package com.chs.service.impl;

import com.chs.model.LoginHistory;
import com.chs.model.User;
import com.chs.model.dto.UserDto;
import com.chs.dao.LoginHistoryMapper;
import com.chs.dao.UserMapper;
import com.chs.exception.ServiceException;
import com.chs.service.UserService;
import com.chs.util.EMailUtil;
import com.chs.util.IpUtil;
import com.chs.util.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil; 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * (User)表服务实现类
 *
 * @author mopeiwen
 * @since 2020-06-10 10:49:15
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Resource
	private UserMapper userMapper;

	@Resource
	private LoginHistoryMapper loginHistoryMapper;
	
    @Autowired
    private HttpServletRequest request;
    
    @Autowired
    private HttpServletResponse response;
	
	/**
	 * 通过用户ID查询用户详细信息
	 *
	 * @param uid 主键
	 * @return 实例对象
	 */
	@Override
	public User queryById(String uid) {
		User user = this.userMapper.selectByPrimaryKey(uid);
		user.setPassword(null);
		return user;
	}

	/**
	 * 通过User对象查询集合
	 *
	 * @param user 实例对象
	 * @return 实例对象
	 */
	@Override
	public PageInfo<User> selectAll(int pageNum, int pageSize) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);
		// 使用PageInfo来封装查询的数据
		PageInfo<User> pageInfo = new PageInfo<User>(userMapper.selectAll());

		return pageInfo;

	}

	/**
	 * 获得验证码
	 * 
	 * @return
	 */
	public boolean getCode(String username) {
		String code = RandomUtil.randomString(6);

		if (username==null) {
			return false;
		}
		
		//("code", code);
		request.getServletContext().setAttribute(username, code);

		try {
			if (Validator.isEmail(username)) { //如果是邮箱
				EMailUtil.sendMail(username, "转手商场-验证码", EMailUtil.context(username, code));
			}else { //如果是手机

			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

	/**
	 * 新增用户数据
	 *
	 * @param user 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean insert(UserDto user) {
		String code = (String) request.getServletContext().getAttribute(user.getUsername());
		if(code==null) {
			throw new ServiceException(-1, "验证码不能为空");
		}
		//辅助查询是否存在同一样的账号
		User user_ = new User();
		
		if (code!=null&&code.equals(user.getCode())) {
			if (Validator.isEmail(user.getUsername())) { //如果是邮箱
				
				user_.setEmail(user.getUsername());
				if (this.userMapper.selectByAccount(user_)!=null) {
					throw new ServiceException(-1, "邮箱重复");
				}
				
				user.getUser().setEmail(user.getUsername());
			}else { //如果是手机
				
				user_.setPhone(user.getUsername());
				if (this.userMapper.selectByAccount(user_)!=null) {
					throw new ServiceException(-1, "手机重复");
				}
				
				user.getUser().setPhone(user.getUsername());
			}
	
			user.getUser().setRegistertime(DateUtil.now());
			
			return this.userMapper.insertSelective(user.getUser())>0;
		} else {
			return false;
		}
	}
	
	@Override
	public boolean insert(User user) {
		user.setRegistertime(DateUtil.now());
		return this.userMapper.insertSelective(user)>0;
	}

	/**
	 * 修改用户信息数据
	 *
	 * @param user 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean update(User user) {
		if (user.getUid()==null||user.getUid().equals("")) {
			user.setUid(TokenUtil.getUserId(request.getHeader("Authorization")));
		}
		
		if (user.getPassword()!=null&&!user.getPassword().equals("")) {
			String regexp = "^(?![a-zA-Z]+$)(?![0-9]+$)[A-Za-z0-9]{8,18}$";
			
			if (!Pattern.matches(regexp,user.getPassword())) {
				throw new ServiceException(-1, "密码必须为8-18为数字与字母组合");
			}
		}
		
		return this.userMapper.updateByPrimaryKeySelective(user)>0?true:false;
	}

	
	//找回密码
	@Override
	public boolean updatePassword(UserDto user) {
		System.out.println(user.getUsername());
		if (user.getUsername()==null||user.getUsername().equals("")) {
			throw new ServiceException(-1, "邮箱不能为空");
		}
		
		User user_ = null;
		String code = (String) request.getServletContext().getAttribute(user.getUsername());
		if (code!=null&&code.equals(user.getCode())) {
			if (Validator.isEmail(user.getUsername())) { //如果是邮箱
				user_ = this.userMapper.selectByEmail(user.getUsername());
			}else { //如果是手机
				user_ = this.userMapper.selectByPhone(user.getUsername());
			}
		} else {
			return false;
		}

		return this.userMapper.updateByPrimaryKeySelective(user_)>0;
	}
	
	@Override
	public boolean updatePhoneOrEmail(UserDto user) {
		User user_ = this.userMapper.selectByPrimaryKey(TokenUtil.getUserId(request.getHeader("Authorization")));
		String code = (String) request.getServletContext().getAttribute(user.getUsername());
		
		if (code!=null&&code.equals(user.getCode())) {
			if (Validator.isEmail(user.getUsername())) { //如果是邮箱
				user_.setEmail(user.getUsername());
			}else { //如果是手机
				user_.setPhone(user.getUsername());
			}
		} else {
			throw new ServiceException(-1, "邮箱或手机不能为空");
		}
		
		return this.userMapper.updateByPrimaryKeySelective(user_)>0;
	}
	
	/**
	 * 通过主键（用户id）删除用户数据
	 *
	 * @param uid 主键
	 * @return 是否成功
	 */
	@Override
	public boolean deleteById(String uid) {
		return this.userMapper.deleteByPrimaryKey(uid) > 0;
	}

	/**
	 * 通过账号来实现用户登录
	 *
	 * @param uid 主键
	 * @return 是否成功
	 * @throws UnsupportedEncodingException 
	 */
	@Override
	public UserDto selectByAccount(String account, String password) throws UnsupportedEncodingException {
		User userVo = new User();

		userVo.setOpenid(account);
		userVo.setQqopenid(account);
		userVo.setEmail(account);
		userVo.setPhone(account);
		userVo.setPassword(password);

		UserDto userDto = null;
		User user = userMapper.selectByAccount(userVo);

		if (user != null) {
			user.setPassword(null);
			userDto = new UserDto(user, null, null);

			//添加登陆记录
			LoginHistory loginHistory = new LoginHistory(user.getUid(), IpUtil.getIpAddr(this.request), IpUtil.getClientOS(this.request), DateUtil.now());
					
			loginHistoryMapper.insertSelective(loginHistory);
		} else {
			throw new ServiceException(-1, "密码或者用户名错误");
		}
		response.setHeader("Authorization", TokenUtil.sign(user.getUid()));
		return userDto;
	}
	
	/**
	 * 管理员批量删除用户
	 */
	@Override
	public boolean batchdeleteUser(String uid) {
		ArrayList<String> uidList = new ArrayList<String>();
		String[] strs = uid.split(",");
		for (String str : strs) {
			uidList.add(str);
		}
		return userMapper.batchdeleteUser(uidList)>0;
	}

}